<!--
 * @Author: Dorange.Wang
 * @Date: 2021-07-09 15:20:10
 * @LastEditors: your name
 * @LastEditTime: 2021-07-19 19:40:06
 * @Description: file content
-->
<template>
  <van-number-keyboard
    :value="value"
    :show="show"
    theme="custom"
    :extra-key="extraKey"
    close-button-text="完成"
    @blur="show = false"
    @input="onInput"
    @delete="onDelete"
  >
    <template v-slot:title-left
      ><span>{{ value }}</span></template
    >
  </van-number-keyboard>
</template>

<script>
const DEFAULT_OPTIONS = {
  title: "", // 标题
  value: undefined, // 当前值
  max: undefined, // 最大值
  min: undefined, // 最小值
  precision: 0, // 精度
};
export default {
  name: "HanKeyboard",

  data() {
    return {
      show: false,
      value: undefined,
      options: {
        ...DEFAULT_OPTIONS,
      },
    };
  },

  computed: {
    extraKey() {
      const { min, precision } = this.options;
      const keys = [];
      if (min < 0) {
        keys.push("-");
      }
      if (precision > 0) {
        keys.push(".");
      }
      return keys.length > 0 ? keys : "";
    },
  },

  methods: {
    init(options = {}) {
      this.show = true;
      this.options = {
        ...DEFAULT_OPTIONS,
        ...options,
      };
      this.value = String(options.value);
    },

    emitChange() {
      const { onChange } = this.options;
      if (!onChange) {
        return;
      }
      this.$nextTick(() => {
        onChange(this.value);
      });
    },

    onInput(value) {
      const newVal = this.value + value;
      if (/^(-?\d+)(\.\d+)?$/.test(this.value + value)) {
        this.value = newVal;
      }
    },

    onDelete() {
      // this.emitChange();
    },
  },
};
</script>

<style lang="less" scoped></style>
